<template>
  <div ref="editorContainer" style="min-height: 200px; width: 100%"></div>
</template>

<script lang="ts" setup>
import * as monaco from 'monaco-editor' // 全部导入
import { ref, onMounted } from 'vue'

const props = defineProps<{
  modelValue: string
  language: string
}>()

const editorContainer = ref<HTMLDivElement>()

// const editor = ref<monaco.editor.IStandaloneCodeEditor | null>(null);
// 可能是 editor 对象太大, 改用响应式时, 调用函数时间过长, 不采用
let editor: monaco.editor.IStandaloneCodeEditor | null = null

const emits = defineEmits(['update:modelValue'])
function debounce(fn: (...args: unknown[]) => void, delay: number) {
  let timer: ReturnType<typeof setTimeout> | null = null
  return function (...args: unknown[]) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

onMounted(() => {
  // [Monaco Editor 配置](https://wf0.github.io/)
  editor = monaco.editor.create(editorContainer.value!, {
    value: props.modelValue || '',
    language: props.language || 'java',
    // 缩略图
    minimap: {
      enabled: false,
    },
    // 行号
    lineNumbers: 'off',
    // 取消行号后的宽度
    lineDecorationsWidth: 0,
    // 配置括号对着色
    bracketPairColorization: {
      enabled: true,
      independentColorPoolPerBracketType: false,
    },
    // 折叠
    folding: false,
    fontSize: 15,
    colorDecorators: true,
    readOnly: false,
    theme: 'vs-light',
  })

  console.log(editor)

  // 防抖处理内容变化事件
  const debouncedEmit = debounce(() => {
    emits('update:modelValue', editor?.getValue())
  }, 800)

  editor.onDidChangeModelContent(() => {
    debouncedEmit()
  })
})
</script>
